package com.morsth.service;

import com.alibaba.fastjson.JSONObject;
import com.morsth.util.ToolsUtils;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter("/*")
public class checkFilter implements Filter {
    Logger  logger  = Logger.getLogger(checkFilter.class);
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //过滤
        HttpServletRequest req  = (HttpServletRequest)   servletRequest;
        HttpServletResponse  resp = (HttpServletResponse) servletResponse;
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        JSONObject  jsonObject  = new JSONObject();
        String uuid = req.getHeader("uuid");
        String fromIP  =req.getRemoteAddr();//访问者IP

        if(uuid == null || "".equals(uuid)){
            jsonObject.put("status","erro");
            jsonObject.put("result","没有传递uuid参数");
            resp.getWriter().write(jsonObject.toJSONString());
            logger.info("访问者IP:" + fromIP+"," + jsonObject.toJSONString());
        }
        else
        {
            //判断uuid参数是否合法
            if(ToolsUtils.checkUuid(uuid)  == false){

                jsonObject.put("status","erro");
                jsonObject.put("result","uuid参数非法");
                resp.getWriter().write(jsonObject.toJSONString());
                logger.info("访问者IP:" + fromIP+"," + jsonObject.toJSONString());

            }else{
                String dateStr = req.getParameter("date");
                if(dateStr == null  ||  "".equals(dateStr)){
                    //如果日期为空
                    jsonObject.put("status","erro");
                    jsonObject.put("result","查询参数为空");
                    resp.getWriter().write(jsonObject.toJSONString());
                    logger.info("访问者IP:" + fromIP+"," + jsonObject.toJSONString());

                }else{
                    if(!ToolsUtils.checkDate(dateStr)){

                        jsonObject.put("status","erro");
                        jsonObject.put("result","日期格式不对,应该是yyyy-MM-dd格式");
                        resp.getWriter().write(jsonObject.toJSONString());
                        logger.info("访问者IP:" + fromIP+"," + jsonObject.toJSONString());
                    }else{

                        filterChain.doFilter(servletRequest,servletResponse);
                    }




                }
            }




        }



    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
